package com.bigdatastudio.gateway.controller;

import com.netflix.hystrix.exception.HystrixTimeoutException;
import org.springframework.cloud.gateway.support.ServerWebExchangeUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.server.ServerWebExchange;
import org.springframework.web.server.ServerWebExchangeDecorator;
import reactor.core.publisher.Mono;

import java.util.HashMap;
import java.util.Map;

/**
 * 快速失败接口
 * @author: zealon
 * @since: 2020/4/11
 */

@RestController
public class FallbackController {

    /**
     *  解决Get请求宕机走熔断
     * @param exchange
     * @return
     */
    @GetMapping("/fallback")
    public Mono<Map<String, Object>> fallback01(ServerWebExchange exchange) {
        Map<String, Object> result = new HashMap<>(2);
        result.put("code", 401);
        Exception exception = exchange.getAttribute(ServerWebExchangeUtils.HYSTRIX_EXECUTION_EXCEPTION_ATTR);
        ServerWebExchange delegate = ((ServerWebExchangeDecorator) exchange).getDelegate();
        if (exception instanceof HystrixTimeoutException) {
            result.put("msg", "接口调用超时,请稍后重试！！");
        } else if (exception != null && exception.getMessage() != null) {
            result.put("msg", "接口调用失败: " + exception.getMessage());
        } else {
            result.put("msg", "接口调用失败");
        }
        return Mono.just(result);
    }

    /**
     *  解决Post请求宕机走熔断
     * @param exchange
     * @return
     */
    @PostMapping("/fallback")
    public Mono<Map<String, Object>> fallback02(ServerWebExchange exchange) {
        Map<String, Object> result = new HashMap<>(2);
        result.put("code", 401);
        Exception exception = exchange.getAttribute(ServerWebExchangeUtils.HYSTRIX_EXECUTION_EXCEPTION_ATTR);
        ServerWebExchange delegate = ((ServerWebExchangeDecorator) exchange).getDelegate();
        if (exception instanceof HystrixTimeoutException) {
            result.put("msg","接口调用超时,请稍后重试！！");
        } else if (exception != null && exception.getMessage() != null) {
            result.put("msg", "接口调用失败: " + exception.getMessage());
        } else {
            result.put("msg", "接口调用失败");
        }
        return Mono.just(result);
    }
}
